package com.cskaoyan.mall.product.controller;

import com.cskaoyan.mall.common.result.Result;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@RestController
@RequestMapping("admin/product")
public class FileUploadController {

    //  获取文件上传对应的地址
    @Value("${minio.endpointUrl}")
    public String endpointUrl;

    @Value("${minio.accessKey}")
    public String accessKey;

    @Value("${minio.secreKey}")
    public String secreKey;

    @Value("${minio.bucketName}")
    public String bucketName;


    @PostMapping("fileUpload")
    public Result upload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

        // 获取用来访问minio server的client对象
        MinioClient minioClient = MinioClient.builder()
                .endpoint(endpointUrl)
                .credentials(accessKey, secreKey)
                .build();


        // 判断桶是否存在
        boolean exists = minioClient.bucketExists(BucketExistsArgs
                .builder().bucket(bucketName).build());

        if (!exists) {
            // 如果桶不存在，则创建桶
            minioClient.makeBucket(MakeBucketArgs
                    .builder().bucket(bucketName).build());
        }

        // 获取文件输入流对象
        InputStream inputStream = file.getInputStream();

        // 为每一个文件生成对应的对象名
        String fileName = System.currentTimeMillis()
                + UUID.randomUUID().toString().replace("-", "");


        // 向目标桶中上传文件
        minioClient.putObject(PutObjectArgs
                .builder()
                // 指定上传文件的桶
                .bucket(bucketName)
                // 指定上传的文件流
                .stream(inputStream, file.getSize(), -1)
                // 指定对象名称
                .object(fileName)
                // 文件类型
                .contentType(file.getContentType())
                .build());


        // 构造用于访问该图片的url，并返回给前端
        String url = endpointUrl + "/" + bucketName + "/" + fileName;


        // 关闭文件流
        inputStream.close();


        return Result.ok(url);
    }
}
